package com.woniuxy.gateway.filter;

import cn.hutool.jwt.JWTUtil;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

import static com.woniuxy.common.constant.FinanceConstant.User.TOKEN;
import static com.woniuxy.common.constant.FinanceConstant.User.WONIUXY;


/**
 * @author ：yolo
 * @date ：Created in 2025/6/26 15:11
 * @description：认证
 * @modified By：
 * @version: $
 */
@Slf4j
@Component
@Order(1)
public class LoginFilter implements GlobalFilter {




    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //认证 1、获取token JWT 2、验证token3、验证通过放行，验证失败返回403
        ServerHttpRequest request = exchange.getRequest();
        //白名单 放行路径
        String path = request.getPath().toString();

        // 白名单路径，不需要验证token
        if (path.contains("/login") || path.contains("/verification/send-code") || path.contains("/verification/login")||path.contains("/uploadImg")||path.contains("/faceLogin")) {
            return chain.filter(exchange);
        }

        String token = request.getHeaders().getFirst(TOKEN);
        if (token == null || token.isEmpty()) {
            return getVoidMono(exchange);
        }

        try {
            boolean verify = JWTUtil.verify(token, WONIUXY.getBytes());
            if (!verify) {
                return getVoidMono(exchange);
            }
        } catch (Exception e) {
            log.error("token验证失败", e);
            return getVoidMono(exchange);
        }

        return chain.filter(exchange);
    }

    private Mono<Void> getVoidMono(ServerWebExchange exchange) {
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        String jsonStr = "{\"status\":\"-1\", \"msg\":\"token非法\"}";
        byte[] bytes = jsonStr.getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
        return exchange.getResponse().writeWith(Flux.just(buffer));
    }
}
